package com.douyinkan.controller;

import com.douyinkan.service.ContentService;
import com.douyinkan.dto.ContentDTO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.io.File;

@RestController
@RequestMapping("/api/thumbnails")
public class ThumbnailController {
    
    private static final Logger logger = LoggerFactory.getLogger(ThumbnailController.class);
    
    @Autowired
    private ContentService contentService;
    
    @GetMapping("/{id}")
    public ResponseEntity<Resource> getThumbnail(@PathVariable Long id) {
        logger.info("Getting thumbnail for content id: {}", id);
        
        ContentDTO content = contentService.getContentById(id);
        if (content == null) {
            logger.warn("Content not found with id: {} when trying to access thumbnail", id);
            return ResponseEntity.notFound().build();
        }
        
        String thumbnailPath = content.getThumbnailPath();
        if (thumbnailPath == null || thumbnailPath.isEmpty()) {
            logger.warn("No thumbnail path found for content id: {}", id);
            return ResponseEntity.notFound().build();
        }
        
        File thumbnailFile = new File(thumbnailPath);
        if (!thumbnailFile.exists()) {
            logger.warn("Thumbnail file not found at path: {} for content id: {}", thumbnailPath, id);
            return ResponseEntity.notFound().build();
        }
        
        try {
            Resource resource = new FileSystemResource(thumbnailFile);
            
            logger.info("Successfully retrieved thumbnail: {} for content id: {}", 
                       thumbnailFile.getName(), id);
            
            return ResponseEntity.ok()
                    .contentType(MediaType.IMAGE_JPEG)  // 缩略图统一为JPG格式
                    .header(HttpHeaders.CONTENT_DISPOSITION, "inline; filename=\"" + thumbnailFile.getName() + "\"")
                    .contentLength(thumbnailFile.length())
                    .body(resource);
        } catch (Exception e) {
            logger.error("Error retrieving thumbnail for content id: {}", id, e);
            return ResponseEntity.internalServerError().build();
        }
    }
}